<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="cn.work.bean.servicebean" %>
<%
    String message = (String) request.getAttribute("message");
    if (message != null && !message.isEmpty()) {
%>
<div class="message"><%= message %></div>
<%
    }
%>

<html>
<head>
    <script>
        var contextPath = "<%= request.getContextPath() %>"; // 在这里直接获取上下文路径
    </script>
    <style>
        /* 确保这些字段没有被隐藏 */
        #serviceTable td {
            display: table-cell;
            visibility: visible;
        }

    </style>
    <title>服务管理</title>
    <link rel="stylesheet" href="../css/admin_yuyue.css" />
    <link rel="stylesheet" href="../css/admin_nav.css" />
    <link rel="stylesheet" href="../css/servlet_manage.css" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<jsp:include page="admin.jsp" />
<div class="content">
    <jsp:include page="admin_nav.jsp" />
    <div class="main">
        <form action="" method="post">
            <div class="servlet_on">
                <input class="search"  type="text" placeholder="请输入搜索内容" name="btn0"/>
                <input id="searchbtn" type="button" value="搜索" name="search" >
                <input class="add" type="button" value="新增" name="add" onclick="showAddForm()"/>
                <input class="delete" type="button" value="批量删除" name="delete" id="deleteBtn"/>
            </div>

            <br />

            <div class="servlet_down">
                <table id="serviceTable">
                    <thead>
                    <tr class="one">
                        <th><input type="checkbox"/>&nbsp;&nbsp;订单编号</th>
                        <th>服务名称</th>
                        <th>分类</th>
                        <th>图片</th>
                        <th>对应医师</th>
                        <th>时长</th>
                        <th>价格</th>
                        <th>简介</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="tbody">
<%--                这里填充新数据--%>
                    </tbody>
                </table>
            </div>
        </form>
    </div>

<%--新增表单--%>
    <div id="addServiceForm" style="display:none;">
        <form action="../ServiceAddServlet?method=save" method="post" enctype="multipart/form-data">
            <h2>新增服务</h2>
            <label>*服务名称：<input type="text" name="name" required /></label><br />
            <label>*分类<input type="text" name="classname" required></label>
            <label>图片：<input type="file" name="image" ></label>
            <label>医生：<input type="text" name="doctor" required /></label><br />
            <label>时长：<input type="number" name="time" required /></label><br />
            <label>价格：<input type="number" name="price" required /></label><br />
            <label>简介：<textarea name="introduction" ></textarea></label><br />
            <label>*状态：
                <select name="status" required>
                    <option value="正常">正常</option>
                    <option value="暂停">暂停</option>
                </select>
            </label><br />
            <input class="btn" type="submit" value="确认新增" />
            <input class="btn" type="button" value="取消" onclick="hideAddForm()" />
        </form>
    </div>

    <%-- 编辑表单 --%>
    <div id="editServiceForm" style="display:none;">
        <form action="../ServiceEditServlet?method=edit" method="post" enctype="multipart/form-data">
            <h2>编辑服务</h2>

            <!-- 获取 serviceId，并作为隐藏字段传递 -->
            <input type="hidden" name="id" id="editServiceId" value="<%= request.getAttribute("serviceid") %>" /> <!-- 使用 request.getAttribute() 获取 serviceId -->

            <!-- 服务名称 -->
            <label>*服务名称：<input type="text" name="name" value="<%= request.getAttribute("serviceName") %>" /></label><br />

<%--            <!-- 服务分类 -->--%>
<%--            <label>*分类：<input type="text" name="classname" value="<%= request.getAttribute("serviceClassName") %>" /></label><br />--%>
<%--            --%>
            <!-- 图片上传 -->
            <label>图片：<input type="file" name="image"></label><br />

            <!-- 医生名称 -->
            <label>医生：<input type="text" name="doctor" value="<%= request.getAttribute("serviceDoctor") %>" /></label><br />

            <!-- 时长 -->
            <label>时长：<input type="number" name="time" value="<%= request.getAttribute("serviceTime") %>" /></label><br />

            <!-- 价格 -->
            <label>价格：<input type="number" name="price" value="<%= request.getAttribute("servicePrice") %>" /></label><br />

            <!-- 简介 -->
            <label>简介：<textarea name="introduction"><%= request.getAttribute("serviceIntroduction") %></textarea></label><br />

            <!-- 状态 -->
            <label>*状态：
                <select name="status">
                    <option value="正常" <%= "正常".equals(request.getAttribute("serviceStatus")) ? "selected" : "" %>>正常</option>
                    <option value="暂停" <%= "暂停".equals(request.getAttribute("serviceStatus")) ? "selected" : "" %>>暂停</option>
                </select>
            </label><br />

            <!-- 提交和取消按钮 -->
            <input class="btn" type="submit" value="提交修改" />
            <input class="btn" type="button" value="取消" onclick="hideEditForm()" />
        </form>
    </div>

</div>

<script>
    function showEditForm(button) {
        // 获取按钮的 data-id 属性
        var serviceId = button.getAttribute('data-id');
        console.log("serviceId: " + serviceId);  // 确认 serviceId 是否正确

        // 填充到隐藏字段
        document.getElementById('editServiceId').value = serviceId;

        // 其他字段的填充逻辑
        var row = button.closest('tr');  // 获取当前按钮所在的行
        var serviceName = row.cells[1].innerText;  // 获取服务名称（第2列）
        var serviceDoctor = row.cells[3].innerText;  // 获取医生名称（第4列）
        var serviceTime = row.cells[4].innerText;  // 获取时长（第5列）
        var servicePrice = row.cells[5].innerText;  // 获取价格（第6列）
        var serviceIntroduction = row.cells[6].innerText;  // 获取简介（第7列）
        var serviceStatus = row.cells[7].innerText;  // 获取状态（第8列）

        // 填充表单
        document.getElementById('editServiceName').value = serviceName;
        document.getElementById('editServiceDoctor').value = serviceDoctor;
        document.getElementById('editServiceTime').value = serviceTime;
        document.getElementById('editServicePrice').value = servicePrice;
        document.getElementById('editServiceIntroduction').value = serviceIntroduction;
        document.getElementById('editServiceStatus').value = serviceStatus;

        // 显示编辑表单
        document.getElementById('editServiceForm').style.display = 'block';
    }
</script>


<script>

    // 新增服务
    function showAddForm() {
        document.getElementById("addServiceForm").style.display = "block";
    }

    function hideAddForm() {
        document.getElementById("addServiceForm").style.display = "none";
    }
//     编辑
    function showEditForm(){
        document.getElementById("editServiceForm").style.display = "block";
    }
    function hideEditForm(){
        document.getElementById("editServiceForm").style.display = "none";
    }

</script>
<%--显示数据--%>
<script>
    var contextPath = "<%= request.getContextPath() %>";
    console.log("contextPath:", contextPath);

    function displayServices() {
        $.ajax({
            url: contextPath + '/ServiceListServlet', // 后端请求的路径
            method: 'GET',
            success: function(response) {
                if (Array.isArray(response)) {
                    console.log("查询成功：", response);
                    $('#serviceTable tbody').empty(); // 清空表格
                    if (response.length > 0) {
                        response.forEach(function(service) {
                            console.log(1)
                            console.log(service.name);
                            var row = '<tr>' +
                                '<td><input type="checkbox" name="serviceId" value="' + service.id + '">' + service.id + '</td>' +
                                '<td>' + service.name + '</td>' +
                                '<td>' + service.classname + '</td>' +
                                '<td><img src="../' + service.image + '" alt="' + service.name + '" width="100" height="100"></td>' +
                                '<td>' + service.doctor + '</td>' +
                                '<td>' + service.time + '</td>' +
                                '<td>' + service.price + '</td>' +
                                '<td style="max-width: 50px;overflow: auto" >' + ' <div id="intro-text">'+ service.introduction +'</div>'+ '</td>' +
                                '<td>' + service.status + '</td>' +
                                '<td class="caozuo">' +
                                '<button class="edit" type="button" onclick="showEditForm()" data-id="' + service.id + '">编辑</button>' +
                                '<button class="delete1" name="delete1" data-id="' + service.id + '">删除</button>' +
                                '</td>' +
                                '</tr>';
                            $('#serviceTable tbody').append(row);
                        });
                    } else {
                        var row = `<tr><td colspan="9">没有数据</td></tr>`;
                        $('#serviceTable tbody').append(row);
                    }
                } else {
                    alert("数据格式错误，请检查服务端返回的数据！");
                }
            },
            error: function(xhr, status, error) {
                console.error("请求出错：", status, error);
                alert("请求出错，请稍后再试！");
            }
        });
    }

    $(document).ready(function() {
        displayServices();  // 页面加载时自动调用，加载所有服务数据
    });
</script>
<%--搜索--%>
<script>
    $(document).ready(function() {
        var contextPath = "<%= request.getContextPath() %>"; // 获取上下文路径

        // 搜索按钮点击事件
        $('#searchbtn').on('click', function () {
            var searchQuery = $('.search').val(); // 获取搜索框中的值
            if (searchQuery.trim() === '') {
                displayServices();
                return;
            }
            searchReservations(searchQuery);
        });

        // 按回车键也触发搜索
        $('#searchInput').on('keypress', function (e) {
            if (e.which === 13) {  // 按下回车键
                $('#searchbtn').click();
            }
        });

        // 展示所有服务
        $(document).ready(function() {
            displayServices();
        });

        // 搜索服务
        function searchReservations(query) {
            $.ajax({
                url: contextPath + '/ServiceDeleteServlet',
                method: 'POST',
                data: { query: query },  // 发送查询参数
                dataType: 'json',  // 确保处理响应时以 JSON 形式返回
                success: function(response) {
                    if (Array.isArray(response)) {
                        console.log("查询成功：", response);
                        $('#tbody').empty();  // 清空表格
                        if (response.length > 0) {
                            response.forEach(function(service) {
                                var row = '<tr>' +
                                    '<td><input type="checkbox" name="serviceId" value="' + service.id + '">' + service.id + '</td>' +
                                    '<td>' + service.name + '</td>' +
                                    '<td>' + service.classname + '</td>' +
                                    '<td><img src="../' + service.image + '" alt="' + service.name + '" width="100" height="100"></td>' +
                                    '<td>' + service.doctor + '</td>' +
                                    '<td>' + service.time + '</td>' +
                                    '<td>' + service.price + '</td>' +
                                    '<td>' + service.introduction + '</td>' +
                                    '<td>' + service.status + '</td>' +
                                    '<td class="caozuo">' +
                                    '<button class="edit" type="button" onclick="showEditForm()" data-id="' + service.id + '">编辑</button>' +
                                    '<button class="delete1" name="delete1" data-id="' + service.id + '">删除</button>' +
                                    '</td>' +
                                    '</tr>';
                                $('#tbody').append(row);
                            });
                        } else {
                            $('#tbody').append('<tr><td colspan="9">没有找到相关服务</td></tr>');
                        }
                    } else {
                        console.log("返回的数据不是数组:", response);
                        alert('查询失败，请检查服务器返回的数据格式');
                    }
                },
                error: function(xhr, status, error) {
                    console.error("请求出错：", status, error);
                    alert("请求出错，请稍后再试！");
                }
            });
        }
    });
</script>

<%--删除--%>
<script>
    var contextPath = "<%= request.getContextPath() %>";
    $(document).ready(function() {
        // 为每个删除按钮绑定点击事件
        $('#serviceTable').on('click', '.delete1', function () {
            var serviceId = $(this).data('id');  // 获取该按钮对应的服务ID
            if (confirm('确认删除该服务吗？')) {
                console.log("Request URL: ", contextPath + '/ServiceDeleteServlet1');
                // 发送 AJAX 请求删除服务
                $.ajax({
                    url: contextPath + '/ServiceDeleteServlet1',
                    method: 'POST',
                    contentType: 'application/json', // 设置为 JSON 格式
                    data: JSON.stringify({ id: serviceId }), // 发送 JSON 数据
                    success: function(response) {
                        if (response.success) {
                            alert('删除成功');
                            $(this).closest('tr').remove();
                        } else {
                            alert('删除失败：' + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("请求出错：", status, error);
                        alert("请求出错，请稍后再试！");
                    }
                });

            }
        });
    });
</script>



<%--批量删除--%>
<script>
    $(document).ready(function() {
        // 绑定批量删除按钮的点击事件
        $('#deleteBtn').on('click', function() {
            deleteSelected(); // 调用 deleteSelected 函数
        });
    });

    // 选择或取消选择所有复选框
    $('#selectAll').on('change', function() {
        var isChecked = $(this).prop('checked');
        $('#serviceTable input[type="checkbox"]').prop('checked', isChecked);
    });

    function deleteSelected() {
        var selectedIds = [];

        // 获取所有被勾选的复选框
        $('#serviceTable input[type="checkbox"]:checked').each(function() {
            var serviceId = $(this).val();
            if (serviceId) {
                selectedIds.push(serviceId); // 收集选中的服务ID
            }
        });

        console.log("选中的服务ID:", selectedIds); // 打印选中的服务ID

        if (selectedIds.length === 0) {
            alert('请勾选要删除的服务！');
            return;
        }

        // 确认删除
        if (confirm('确认删除选中的服务吗？')) {
            $.ajax({
                url: contextPath + '/ServiceSearchServlet', // 批量删除后端接口
                method: 'POST',
                contentType: 'application/json',  // 确保发送的是 JSON 格式
                data: JSON.stringify({ serviceIds: selectedIds }),  // 转换为 JSON 字符串
                success: function(response) {
                    console.log("删除响应:", response);  // 打印返回的响应
                    if (response.success) {
                        alert('删除成功');
                        // 重新加载服务列表
                        displayServices();
                    } else {
                        alert('删除失败：' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("请求出错：", status, error);
                    alert("请求出错，请稍后再试！");
                }
            });
        }
    }

</script>
</body>
</html>
